/**
 * 
 */
package org.dragonfire.dasm.directives;

import java.util.ArrayList;

import org.dragonfire.dasm.Command;
import org.dragonfire.dasm.DASM;
import org.dragonfire.dasm.Listing;
import org.dragonfire.dasm.DirectiveManager.Directive;

/**
 * @author Darth Android
 * @date Jul 24, 2006
 */
public class Tidouble extends Directive {

	@Override
	public ArrayList<Listing> pass1(Command c) {
		ArrayList<Listing> list = new ArrayList<Listing>();
		for (String param : c.getParams()) {
			String value = evalStatics(param);
			list.add(new Listing(9, new Command(c.getName(), value)));
		}
		return list;
	}

	@Override
	public void pass2(Listing lst, Command c) {
		byte[] output = lst.getMCode();
		double value = evalDouble(c.getParam(0));
		if (value < 0)
			output[0] = (byte) 0x80; // bit 7 on of sign bit
		String valueS = Math.abs(value) + "";
		int decimal = valueS.indexOf('.');
		int scale = 0;
		if (decimal < 0)
			scale = valueS.length();
		else if (decimal == 1 && valueS.charAt(0) == '0') {
			int i = 2;
			scale = -1;
			while (i < valueS.length() && valueS.charAt(i++) == '0')
				scale--;
		}
		else {
			int i = 1;
			while (i < valueS.length() && valueS.charAt(i++) != '.')
				scale++;
		}
		if (scale > 99 || scale < -99)
			throw new RuntimeException(DASM.LANG.getString("ERR_DOUBLE_OUT_OF_RANGE", scale));
		output[1] = (byte) (scale + 0x80); // adjust to base point used
		// by TI (0x80)
		String data = valueS.replaceAll("\\.", "");
		while (data.length() < 14) {
			data += "0";
		}
		for (int k = 0; k < 7; k++) {
			output[k + 2] = java.lang.Byte.parseByte(data.substring(0, 2), 16);
			data = data.substring(2);
		}
	}
}
